package cz.proks.easyhelpdesk.gae.core.manager;

import java.math.BigInteger;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import cz.proks.easyhelpdesk.api.BaseApi;
import cz.proks.easyhelpdesk.api.exception.ApiException;
import cz.proks.easyhelpdesk.api.model.base.AnIdentifiableModel;

public abstract class AManager<Entity extends AnIdentifiableModel> implements BaseApi<Entity> {
	private final Logger log = LoggerFactory.getLogger(getClass());	
	
	protected abstract BaseApi<Entity> getDbApi();

	@Override
	public Entity get(Long id) throws ApiException {
		log.debug("get():: Start with id '{}'", id);
		
		Entity entity = getDbApi().get(id);
		
		log.debug("get():: End with entity '{}'", entity);
		return entity;
	}
	

	@Override
	public Long create(Entity entity) throws ApiException {
		log.debug("create():: Start with entity '{}'", entity);
		
		Long id = getDbApi().create(entity);
		
		log.debug("create():: End with id '{}'", id);
		return id;
	}

	@Override
	public void update(Entity entity) throws ApiException {
		log.debug("update():: Start with entity '{}'", entity);
		
		getDbApi().update(entity);
		
		log.debug("update():: End");		
	}

	@Override
	public void remove(Long id) throws ApiException {
		log.debug("delete():: Start with id '{}'", id);
		
		getDbApi().remove(id);
		
		log.debug("delete():: End");		
	}	
	
	protected long createUniqueID() {
	    String uniqueString = UUID.randomUUID().toString();
	    byte[] idBytes = DigestUtils.md5Digest(uniqueString.getBytes());
	    long id = 0;
	    
	    for (int index = 0; index < idBytes.length; index++)
	        id |= ( (long) (idBytes[index]) & 0x0FF) << (8 * index);
	    	    	    
	    return Math.abs(id);
	}
	
	protected int createUniqueIntegerID() {
	    return Math.abs(BigInteger.valueOf(createUniqueID()).intValue());
	}
}
